package com.ebraga.trackerclub.android.view.fragment;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.ebraga.trackerclub.android.R;
import com.ebraga.trackerclub.android.handler.service.ChronometerServiceHandler;
import com.ebraga.trackerclub.android.util.AndroidApplication;
import com.ebraga.trackerclub.android.util.DLog;
import com.ebraga.trackerclub.android.util.DateUtils;
import com.ebraga.trackerclub.android.util.ISmartServiceConstants;
import com.ebraga.trackerclub.android.util.SmartServiceJavascriptInterface;
import com.ebraga.trackerclub.android.util.UtilView;
import com.ebraga.trackerclub.android.util.api.AndroidContext;
import com.ebraga.trackerclub.android.util.core.AndroidContextImpl;
import com.ebraga.trackerclub.android.view.MainActivity;
import com.ebraga.trackerclub.android.view.MyWebViewClient;
import com.ebraga.trackerclub.android.vo.ChronometerVO;
import com.ebraga.trackerclub.android.vo.PositionVO;
import com.ebraga.trackerclub.android.vo.UserVO;

/**
 * Fragment that appears in the "content_frame"
 */
@SuppressLint("SetJavaScriptEnabled")
public class ChronometerFragment extends Fragment {
	WebView webView;
	Date lastGpsMessage 				= null;
	final int TIME_SHOW_GPS_MESSAGE 	= 15;	
	PositionVO startGpsData				= null;
	PositionVO endGpsData				= null;
	boolean canStart					= false;
	boolean canStop						= false;
	
    public ChronometerFragment() {
        // Empty constructor required for fragment subclasses
    	
    }

	private ChronometerServiceHandler chronometerServiceHandler() {
		
		AndroidContext context = new AndroidContextImpl();
		   
		context.setContext(getActivity().getApplicationContext());				

		ChronometerServiceHandler chronometerServiceHandler = new ChronometerServiceHandler(context);
		
		return chronometerServiceHandler;
		
	}     

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	
    	((MainActivity)getActivity()).setCurrentScreen(ISmartServiceConstants.SCREEN_TAG.CHRONOMETER);
    	
    	View mainView = (View) inflater.inflate(R.layout.fragment_webview, container, false);
        webView = (WebView) mainView.findViewById(R.id.webview);
        webView.setWebViewClient(new MyWebViewClient());
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavascriptInterface(inflater.getContext()), "AndroidNativeCode");
       	webView.loadUrl("file:///android_asset/chronometer.html");
        
        return mainView;
    }
    


	private void controlMessageGps() {

		if ((lastGpsMessage == null) || (DateUtils.diffBetweenDate(lastGpsMessage, new Date(), Calendar.SECOND) > TIME_SHOW_GPS_MESSAGE)) {
			lastGpsMessage = new Date();	
			UtilView.showMessage(webView, getActivity().getApplicationContext(), ISmartServiceConstants.ERROR_CODE.WAIT_STOPPED_CAR);
		}
		
	}
	
	public class JavascriptInterface extends SmartServiceJavascriptInterface {
		 
		public JavascriptInterface(Context c) {
			super(c);
		}
		

		private JSONObject getAllGpsInfo() throws JSONException {
			JSONObject jObject = new JSONObject();
			
			if (!UtilView.checkRestriction(getActivity().getApplicationContext())) {
				webView.loadUrl("file:///android_asset/restriction.html");
			} else {
			
				AndroidApplication androidApplication = (AndroidApplication) getActivity().getApplicationContext();
				PositionVO gpsInfoVO = (PositionVO) androidApplication.getGpsInfoVO();

				Double speed = 0.0;
				try {
					speed = Double.parseDouble(gpsInfoVO.getSpeed());
				
				} catch (Exception e) {
					speed = 0.0;
				}
				
				jObject.put("Imei", gpsInfoVO.getImei());
				jObject.put("Latitude", gpsInfoVO.getLatitude());
				jObject.put("Longitude", gpsInfoVO.getLongitude());
				jObject.put("Accuracy", gpsInfoVO.getAccuracy());
				jObject.put("Provider", gpsInfoVO.getProvider());
				jObject.put("Speed", speed.intValue());
				
			}
			return jObject;
		}
		

		public void getSpeedInfo() {
			try {
				
				JSONObject jObject = getAllGpsInfo();
				webView.loadUrl("javascript:setSpeedInfo(" + jObject + ")");

			} catch (Exception e) {
				DLog.e(e);
				controlMessageGps();
				
			}

		}		
		

		public void checkStart() {
			try {

				if (!UtilView.checkRestriction(getActivity().getApplicationContext())) {
					webView.loadUrl("file:///android_asset/restriction.html");
				} else {
				
					AndroidApplication androidApplication = (AndroidApplication) getActivity().getApplicationContext();
					PositionVO gpsInfoVO = (PositionVO) androidApplication.getGpsInfoVO();
	
					startGpsData = gpsInfoVO;
					double currentSpeed = 0;
					
					if ((gpsInfoVO != null) && 
							(gpsInfoVO.getProvider().equals(getActivity().getApplicationContext().getString(R.string.provider_gps)))) {
						currentSpeed = Double.valueOf(gpsInfoVO.getSpeed());
						
						if (currentSpeed <= 1) {
							canStart = true;
						}
					}
					
					if ((canStart) && (currentSpeed <= 1)) {
						webView.loadUrl("javascript:readyToStart();");		
					} else if ((canStart) && (currentSpeed > 0)) {
						webView.loadUrl("javascript:chronoStart();");			
						canStop = true;
					} else {
						controlMessageGps();
						
					}
					
				}
				
				
			} catch (Exception e) {          
				DLog.e(e);
				
			}			
		}
		
		public void reset() {
			
			startGpsData			= null;
			endGpsData				= null;
			canStart				= false;
			canStop					= false;
			
		}
		
		public void checkStop(String jsonString) {
			try {
				if (canStop) {
					JSONObject jsonObject = new JSONObject(jsonString);
					String speeParam = jsonObject.getString("speed");		
					Double speedDouble = Double.valueOf(speeParam);
					
					if (!UtilView.checkRestriction(getActivity().getApplicationContext())) {
						webView.loadUrl("file:///android_asset/restriction.html");
					} else {
					
						AndroidApplication androidApplication = (AndroidApplication) getActivity().getApplicationContext();
						PositionVO gpsInfoVO = (PositionVO) androidApplication.getGpsInfoVO();
						
						endGpsData = gpsInfoVO;
		
						if (Double.valueOf(gpsInfoVO.getSpeed()) >= speedDouble) {
							webView.loadUrl("javascript:chronoStop()");		
						}
						
					}
				}
				
				
			} catch (Exception e) {          
				DLog.e(e);
				
			}			
		}
		
		public void sendChronometerData(String jsonString) {
				try {
					UserVO userVO = UtilView.getLastUserSession(getActivity().getBaseContext());
					JSONObject jsonObject 	= new JSONObject(jsonString);
					String time 			= jsonObject.getString("Time");
					String typeChronometer 	= jsonObject.getString("TypeChronometer");
					
					time = time.replace(':', '.');
					
					AndroidApplication androidApplication = (AndroidApplication) getActivity().getApplicationContext();
					PositionVO gpsInfoVO = (PositionVO) androidApplication.getGpsInfoVO();
					endGpsData = gpsInfoVO;
					startGpsData = gpsInfoVO;
					
					ChronometerVO chronometerVO = new ChronometerVO();
					chronometerVO.setDateCreated(new Date());
					chronometerVO.setTime(time);
					chronometerVO.setTypeChronometer(typeChronometer);
					chronometerVO.setBrand(userVO.getBrand());
					chronometerVO.setImei(userVO.getImei());
					chronometerVO.setModel(userVO.getModel());
					chronometerVO.setName(userVO.getName());					
					chronometerVO.setEndDate(endGpsData.getDateLastPosition());
					chronometerVO.setEndLatitude(endGpsData.getLatitude());
					chronometerVO.setEndLongitude(endGpsData.getLongitude());
					chronometerVO.setEndSpeed(endGpsData.getSpeed());
					chronometerVO.setStartDate(startGpsData.getDateLastPosition());
					chronometerVO.setStartLatitude(startGpsData.getLatitude());
					chronometerVO.setStartLongitude(startGpsData.getLongitude());
					chronometerVO.setStartSpeed(startGpsData.getSpeed());
											
				
					ChronometerServiceHandler chronometerServiceHandler = chronometerServiceHandler();	
					chronometerServiceHandler.sendChronometerData(chronometerVO);
				} catch (Exception e) {          
					DLog.e(e);
					
				}					
			
		}
		
		public void getTopCronometer() {
			try {
				ChronometerServiceHandler chronometerServiceHandler = chronometerServiceHandler();	
				List<ChronometerVO> list = chronometerServiceHandler.list();
				
				JSONArray listJson = new JSONArray();
				JSONObject jObject;
				int position = 1;
				for (ChronometerVO chronometerVO : list) {
					
					jObject = new JSONObject();
					jObject.put("Position", position);
					jObject.put("Time", chronometerVO.getTime());
					jObject.put("Model", chronometerVO.getModel());
					
					listJson.put(jObject);
					position++;
					
				}

				webView.loadUrl("javascript:setChronometer(" + listJson + ")");				
				
			} catch (Exception e) {          
				DLog.e(e);
			}	
		}
	}

}